package com.atguigu.bigdata.chapter11.window;

import com.atguigu.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.GroupWindow;
import org.apache.flink.table.api.Session;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

/**
 * @Author lzc
 * @Date 2022/9/9 14:09
 */
public class Flink03_Window_TableAPI {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // 流转成表的 时候添加时间时间, 则流中一定要添加水印
        DataStream<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_2", 2000L, 20),
                new WaterSensor("sensor_1", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_2", 6000L, 50),
                new WaterSensor("sensor_1", 7000L, 60),
                new WaterSensor("sensor_1", 8000L, 80)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forMonotonousTimestamps()
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        //        Table table = tEnv.fromDataStream(stream, $("id"), $("ts").rowtime(), $("vc"));
        Table table = tEnv.fromDataStream(stream, $("id"), $("ts"), $("vc"), $("et").rowtime());
        // 定义一个5s的滚动窗口
//        GroupWindow win = Tumble.over(lit(5).second()).on($("et")).as("w");
        // 定义一个长度为5s, 滑动步长为2s的滑动窗口
//        GroupWindow win = Slide.over(lit(5).second()).every(lit(2).seconds()).on($("et")).as("w");
        GroupWindow win = Session.withGap(lit(2).second()).on($("et")).as("w");
        table
            .window(win)
            .groupBy($("id"), $("w"))  // 窗口旧可以作为一个普通的分组字段来使用
            .select($("id"), $("w").start(), $("w").end(), $("vc").sum().as("vc_sum"))
            .execute()
            .print();
        
    }
}
/*
 
 
 */
